// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

// 获取签发卡券
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let limit_num = event.limit;
  let skip_num = event.skip;
  console.log('limit_num:' + limit_num + ';skip_num:' + skip_num);
  let openid = wxContext.OPENID;
  let res = new Object();
  let card_info = await db.collection('ops_card').where({
    Issuer_openid: openid,
  }).get();
  if (card_info.data.length == 0) {
    return 0;
  } else {
    let id_array = [];
    for (i = 0; i < card_info.data.length; i++) {
      id_array[i] = card_info.data[i]._id;
    }
    let lssue_list = await db.collection('ops_card').aggregate().sort({
      status: 1,
      update_time: -1
    }).match({
      _id: _.in(id_array)
    }).project({
      goods_id: 1,
      card_number: 1,
      card_password: 1,
      goods_number: 1,
      card_url: 1,
      qrcode_url: 1,
      status: 1,
      update_time_show: $.dateToString({
        date: '$update_time',
        format: '%Y-%m-%d %H:%M:%S',
        timezone: 'Asia/Shanghai'
      }),
      expiration_date_show: $.dateToString({
        date: '$expiration_date',
        format: '%Y-%m-%d',
        timezone: 'Asia/Shanghai'
      })
    }).lookup({
      from: 'ops_goods',
      localField: 'goods_id',
      foreignField: '_id',
      as: 'goodsList',
    }).replaceRoot({
      newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
    }).project({
      goodsList: 0,
      Issuer_openid: 0,
      goods_explain: 0,
      goods_id: 0,
      goods_url: 0,
      specs: 0
    }).limit(limit_num).skip(skip_num).sort({
      status: 1
    }).end();
    res.lssue_length = id_array.length;
    res.lssue_list = lssue_list.list;
    return res;
  }
}